package pl.edu.agh.uddiProxy.parameter;

import java.util.List;
import java.util.Map;

import pl.edu.agh.uddiProxy.dao.DAOHelper;
import pl.edu.agh.uddiProxy.types.ParameterType;
import pl.edu.agh.uddiProxy.types.PatrameterCollector;
import pl.edu.agh.uddiProxy.types.ServiceDynamicParameters;
import pl.edu.agh.uddiProxy.types.TModel;

public class ServiceRankParameterCollector implements
		PatrameterCollector<Double> {
	private List<String> list;
	
	public ServiceRankParameterCollector(List<String> list) {
		this.list = list;
	}

	public Double getParameter(TModel model) {
		ServiceDynamicParameters dynamicParameters = DAOHelper.getDynamicParameterDAO().getByTModel(model.getModel().getTModelKey());
		Map<String, ParameterType> map = DAOHelper.getParametersMap().getParametersMap();
		
		int count = 0;
		
		double value = 0.0;
		for (String key : list) {
			if (!map.get(key).getType().isNumber() || 
					dynamicParameters.getParameterValue(key).getValue() == null ||
					dynamicParameters.getParameterValue(key).getValue().length() == 0) {
				continue;
			}
			
			double weight = map.get(key).getWeight();
			double v = Double.parseDouble(dynamicParameters.getParameterValue(key).getValue());
			
			ParameterType type = map.get(key);
			Double min = null;
			Double max = null;
			
			if (type.getMinValue() != null) {
				min = Double.parseDouble(type.getMinValue());
			}
			if (type.getMaxValue() != null) {
				max = Double.parseDouble(type.getMaxValue());
			}
			
			if (max == null) {
				max = Double.MAX_VALUE;
			}
			if (min == null) {
				min = Double.MIN_VALUE;
			}
			
			if (type.isSmallerIsBetter()) {
				v = Math.abs(max - v);			
			} else {
				v = Math.abs(v - min);
			}
			
			if (max.equals(min)) {
				v = 1.0;
			} else {
				v = Math.abs(v) / (max - min);
			}
			
			double srMin = Double.parseDouble(map.get("serviceRank").getMinValue());
			double srMax = Double.parseDouble(map.get("serviceRank").getMaxValue());
			
			v = v * (srMax - srMin);
			
			value += v * weight; 
			count++;
		}
		return value / (double) count;
	}

}
